<template>
  <a-modal v-model:visible="show" title="添加点位" :width="950" @ok="ok">
    <div class="w-full">
      <div class="rounded border border-solid border-color-split md:flex md:flex-row md:items-stretch md:h-120">
        <div class="md:w-3/4 flex flex-col">
          <div class="pt-2 px-2 sm:pt-4 sm:px-4 border-0 border-b border-color-split border-solid">
            <div class="pb-2 sm:pb-4">
              <a-input-search
                v-model:value="keyword"
                placeholder="搜索点位名称"
                size="small"
                :allow-clear="true"
                :maxlength="32"
                style="width: 200px"
                @search="keywordSearch"
              >
                <template #enterButton>
                  <a-button>
                    <template #icon><Icon type="icon-sousuo" /></template>
                  </a-button>
                </template>
              </a-input-search>
            </div>
          </div>
          <div class="h-full relative rounded overflow-auto">
            <SlTable
              :class="{ 'ant-table-empty-noborder': tableData.length === 0 }"
              :columns="columns"
              :pagination="(false as any)"
              size="small"
              :data-source="tableData"
              :loading="tableLoading"
              row-key="equipmentTypeAttributeId"
              :row-selection="{
                selectedRowKeys: value,
                onSelect,
                getCheckboxProps,
                onSelectAll,
                hideSelectAll: singleSelect,
              }"
              :custom-row="customRow"
              :search-model="searchModel"
              :ignore-keys="['organizationId']"
            >
              <template #bodyCell="{ column, record }: BodyCellOptions<EquipmentAttrItem>">
                <div v-if="column.dataIndex === 'attributeLevel'">
                  {{ AttributeLevel[record.attributeLevel] || "--" }}
                </div>
                <div v-if="column.dataIndex === 'readWriteType'">
                  {{ ReadWriteType[record.readWriteType] || "--" }}
                </div>
                <div v-if="column.dataIndex === 'dataType'">
                  {{ DataType[record.dataType] || "--" }}
                </div>
              </template>
            </SlTable>
          </div>
        </div>
        <div class="md:w-1/4 border-0 border-t md:border-t-0 md:border-l border-solid border-color-split flex flex-col">
          <div class="py-5.5 flex flex-row items-center pl-4 pr-4.5">
            <div class="flex-1">
              <span class="text-lg font-semibold text-color-header">已选</span>
              <span class="text-color-secondary">({{ selectedEquipmentAttr.length }})</span>
            </div>
            <div class="text-red-400 cursor-pointer" @click="clearSelected"> 清空 </div>
          </div>
          <div v-if="selectedEquipmentAttr.length > 0" class="flex-1 overflow-auto pl-4 pr-4.5">
            <div
              v-for="(el, i) in selectedEquipmentAttr"
              :key="el.equipmentTypeAttributeId"
              class="flex flex-row items-center mb-4"
            >
              <div class="flex-1 overflow-hidden">
                <span class="text-color-main">{{ el.attributeName }}</span>
                <!-- <span v-if="hasOrg" class="text-sm text-color-secondary">({{ el.organizations }})</span> -->
              </div>
              <div class="cursor-pointer w-10 text-right">
                <a v-show="!el.equipmentTypeAttributeId" @click="removeSelected(el, i)">移除</a>
              </div>
            </div>
          </div>
          <SlEmpty v-else />
        </div>
      </div>
    </div>
  </a-modal>
</template>
<script setup lang="ts">
import { nextTick, onMounted, ref, watch, computed, watchEffect } from "vue";
import { useCURD } from "/@/hooks/useCURD";
import SlEmpty from "/@/components/SlEmpty.vue";
import SlTable from "/@/components/SlTable.vue";
import EllipsisText from "/@/components/common/EllipsisText.vue";
import type { BodyCellOptions } from "/@/types/antd";
import { findParents, loopItem } from "/@/utils/treeData";
import type { EquipmentAttrItem } from "/@/api/aiot/equipmentType/models";
import { Api, attrPage, equipmentGroupPage, changeEquipmentTypeAttributesViewBatch } from "/@/api/aiot/equipmentType";
import {
  AttributeLevel,
  ReadWriteType,
  DataType,
  ParEquipmentAttrItem,
  AttrViewReq,
} from "/@/api/aiot/equipmentType/models";
import { message } from "ant-design-vue";

const props = withDefaults(
  defineProps<{
    //所勾选的用户id数组 双向绑定
    visible: boolean;
    value: string[];
    viewCode?: string; // 当前选择的视图
    equipmentTypeId: string;
    singleSelect?: boolean;
  }>(),
  {}
);
const show = ref<boolean>(false);
// columns
const columns = [
  {
    title: "点位名称",
    dataIndex: "attributeName",
    width: 120,
  },
  {
    title: "显示名称",
    dataIndex: "attributeDisplayName",
    width: 120,
  },
  {
    title: "参数分组",
    dataIndex: "equipmentParamGroupsName",
    ellipsis: true,
    width: 120,
  },
  {
    title: "参数级别",
    dataIndex: "attributeLevel",
    ellipsis: true,
    width: 120,
  },
  {
    title: "读写类型",
    dataIndex: "readWriteType",
    ellipsis: true,
    width: 120,
  },
  {
    title: "数据类型",
    dataIndex: "dataType",
    ellipsis: true,
    width: 120,
  },
];
watch(
  () => props.visible,
  (v) => {
    reloadTable({ model: { equipmentTypeId: props.equipmentTypeId }, size: 999, current: 1 });
    show.value = v;
    if (!v) {
      reset();
    }
  }
);

let firstShow = true;
watch(show, (v) => {
  emits("update:visible", v);

  if (firstShow) {
    firstShow = false;
  }
});
const emits = defineEmits(["update:value", "update:visible", "successFn"]);

onMounted(async () => {});
/**
 * search
 */
const keyword = ref("");
function keywordSearch() {
  reloadTable({
    model: {
      equipmentTypeId: props.equipmentTypeId,
      searchText: keyword.value,
    },
  });
}
/**
 * table
 */
const disabledValue = ref<string[]>([]);
const { tableData, tableLoading, pagination, reloadTable, searchModel } = useCURD<EquipmentAttrItem>({
  getPageUrl: Api.attrPage,
  loadOnMounted: false,
  onLoadSuccess(data) {
    // 初始化清空disabledValue
    disabledValue.value = [];
    loopItem(data, (item) => {
      if (props.viewCode && item[props.viewCode]) {
        disabledValue.value.push(item.equipmentTypeAttributeId);
      }
    });
  },
});
function removeSelected(el: EquipmentAttrItem, i) {
  const copyValue = [...props.value];
  const j = copyValue.indexOf(el.equipmentTypeAttributeId as string);
  if (j >= 0) {
    copyValue.splice(j, 1);
  }
  selectedEquipmentAttr.value.splice(i, 1);
  const unCheckedKeys = [el.equipmentTypeAttributeId as string];
  emits("update:value", copyValue);
}
//table select
const selectedEquipmentAttr = ref<EquipmentAttrItem[]>([]);
function getCheckboxProps(record: EquipmentAttrItem) {
  if (disabledValue.value?.includes(record.equipmentTypeAttributeId as string)) {
    return { disabled: true };
  }
}
function onSelectAll(selected: boolean, selectedRows: EquipmentAttrItem[], changeRows: EquipmentAttrItem[]) {
  onUserSelectAll(selected, selectedRows, changeRows, false);
}
function onSelect(record: EquipmentAttrItem, selected: boolean) {
  onUserSelect(record, selected, false);
}
function onUserSelectAll(
  selected: boolean,
  selectedRows: EquipmentAttrItem[],
  changeRows: EquipmentAttrItem[],
  isTree?: boolean
) {
  const copyValue = [...props.value];
  changeRows.forEach((record) => {
    toggleOne(selected, copyValue, record, isTree);
  });
  emits("update:value", copyValue);
}
function onUserSelect(record: EquipmentAttrItem, selected: boolean, isTree?: boolean) {
  const copyValue = [...props.value];
  toggleOne(selected, copyValue, record, isTree);
  emits("update:value", copyValue);
}

function toggleOne(selected: boolean, copyValue: string[], record: EquipmentAttrItem, isTree?: boolean) {
  let index = copyValue.indexOf(record.equipmentTypeAttributeId as string);
  if (selected) {
    if (index === -1) {
      if (props.singleSelect) {
        copyValue[0] = record.equipmentTypeAttributeId as string;
        selectedEquipmentAttr.value = [record];
      } else {
        copyValue.push(record.equipmentTypeAttributeId as string);
        selectedEquipmentAttr.value.push(record);
      }
    }
  } else {
    if (index >= 0) {
      copyValue.splice(index, 1);
      selectedEquipmentAttr.value.splice(index, 1);
    }
  }
}
function customRow(record: EquipmentAttrItem) {
  return {
    onClick() {
      if (disabledValue.value?.includes(record.equipmentTypeAttributeId as string)) {
        return;
      }
      onSelect(record, !props.value.includes(record.equipmentTypeAttributeId as string));
    },
  };
}
function clearSelected() {
  let defaultArr = selectedEquipmentAttr.value.filter((item) => {
    return item.equipmentTypeAttributeId;
  });
  let defaultKey =
    defaultArr?.map((item) => {
      return item.equipmentTypeAttributeId;
    }) || [];
  // selectedEquipmentAttr.value = [...defaultArr];
  selectedEquipmentAttr.value = [];
  emits("update:value", []);
}

async function ok() {
  let data: AttrViewReq = { equipmentTypeAttributeIds: props.value };
  if (props.value && props.value.length < 1) {
    message.warning("请选择点位再做此操作");
    return;
  }
  // 当前选中的视图code
  if (props.viewCode !== "all" && props.viewCode) {
    data[props.viewCode] = true;
  }
  let req = await changeEquipmentTypeAttributesViewBatch(data);
  if (req) {
    message.success("操作成功");
    show.value = false;
    emits("successFn");
  }
}
function reset() {
  emits("update:value", []);
  keyword.value = "";
  selectedEquipmentAttr.value = [];
  keywordSearch();
}
</script>
<style lang="less">
.user-depart-tree {
  .ant-tree-checkbox {
    margin: 4px 4px 0;
  }
  .ant-tree-iconEle {
    width: 18px !important;
    margin-right: 5px;
  }
}
</style>
